package threadLocal;

import java.util.Random;

/**
 * <描述>
 *
 * @author timothy.yang cloudwise
 * @since 2022-11-20 11:32
 */
public class ThreadLocalTest implements Runnable {

    private static final ThreadLocal<Long> threadLocalValue = ThreadLocal.withInitial(() -> new Long(1));

    private static Long threadShardValue = 1l;

    @Override
    public void run() {
        System.out.println("Thread Name= " + Thread.currentThread().getName() + " default threadLocalValue = " + threadLocalValue.get());
        System.out.println("Thread Name= " + Thread.currentThread().getName() + " default threadShardValue = " + threadShardValue);
        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //formatter pattern is changed here by thread, but it won't reflect to other threads
        threadLocalValue.set(2l);
        threadShardValue = 2l;

        System.out.println("Thread Name= " + Thread.currentThread().getName() + " threadLocalValue = " + threadLocalValue.get());
        System.out.println("Thread Name= " + Thread.currentThread().getName() + " threadShardValue = " + threadShardValue);
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadLocalTest obj = new ThreadLocalTest();
        for (int i = 0; i < 5; i++) {
            Thread t = new Thread(obj, "" + i);
            Thread.sleep(new Random().nextInt(1000));
            t.start();
        }
    }

    class TestClassLoader extends ClassLoader {

    }
}
